// pages/teacher/booking/booking.js
Page({
  data: {
    headerHeight: 0,
    list: []
  },

  onLoad() {
    this.loadList()
  },

  onHeaderReady(e) {
    const { totalHeight } = e.detail || {}
    this.setData({ headerHeight: totalHeight || 0 })
  },

  // 从后端加载预约列表（基于 student_survey + student_info）
  async loadList() {
    try{
      const api = require('../../../utils/api')
      const res = await api.survey.list()
      if(res && res.success && Array.isArray(res.data)){
        this.setData({ list: res.data.map(x=>({
          id: String(x.id||''),
          name: x.name || '',
          avatar: x.avatar || '/images/workspace/default-avatar.png',
          studentId: String(x.studentId||''),
          courseName: x.courseName || '',
          timeDesc: x.timeDesc || '',
          status: x.status || 'pending'
        })) })
      } else {
        // 如果后端还未提供列表接口，退化为按 teacherId 拉全部学生+是否有问卷
        await this.loadListFallback()
      }
    }catch(e){ await this.loadListFallback() }
  },

  async loadListFallback(){
    // 简易方案：读取全部学生，逐个查询是否有问卷，有则组织为卡片
    try{
      const api = require('../../../utils/api')
      const all = await api.teacherSchedule.getDay({ date: '' }).catch(()=>({}))
      // 这里需要后端提供“我的学生列表”接口或“所有学生列表”，当前项目已有：MiniStudentServiceImpl.getAllStudents()
      // 但未暴露HTTP端点。请在后端补充一个列表接口：GET /api/mini/student/all
      // 前端占位：不做展示
      this.setData({ list: [] })
    }catch(e){ this.setData({ list: [] }) }
  },

  onApprove(e) {
    const { id } = e.currentTarget.dataset
    const api = require('../../../utils/api')
    wx.showLoading({ title:'处理中...' })
    api.survey.approve(id).then(()=>{
      const list = this.data.list.map(it => it.id === id ? { ...it, status: 'approved' } : it)
      this.setData({ list })
      wx.hideLoading(); wx.showToast({ title: '已同意预约', icon: 'success' })
    }).catch(()=>{ wx.hideLoading(); wx.showToast({ title:'操作失败', icon:'none' }) })
  },

  onReject(e) {
    const { id } = e.currentTarget.dataset
    const api = require('../../../utils/api')
    const that = this
    wx.showModal({
      title: '填写拒绝原因', editable: true, placeholderText: '请输入拒绝原因',
      success(res){
        if(res.confirm){
          const reason = res.content || ''
          wx.showLoading({ title:'处理中...' })
          api.survey.reject(id, reason).then(()=>{
            const list = that.data.list.map(it => it.id === id ? { ...it, status: 'rejected', rejectReason: reason } : it)
            that.setData({ list }); wx.hideLoading(); wx.showToast({ title:'已拒绝', icon:'none' })
          }).catch(()=>{ wx.hideLoading(); wx.showToast({ title:'操作失败', icon:'none' }) })
        }
      }
    })
  },

  // 同意后：填写学习计划
  writePlan(e){
    const { id } = e.currentTarget.dataset
    const item = (this.data.list||[]).find(x=>x.id===id)
    if(!item){ return }
    const students = [{ id: String(item.studentId||''), name: item.name, avatar: item.avatar }]
    const param = encodeURIComponent(JSON.stringify(students))
    wx.navigateTo({ url: `/pages/teacher/schedule-plan/schedule-plan?students=${param}` })
  },

  // 同意后：查看问卷
  viewSurvey(e){
    const { id } = e.currentTarget.dataset
    const item = (this.data.list||[]).find(x=>x.id===id)
    if(!item){ return }
    // 从后端按学生ID查询问卷
    wx.navigateTo({ url: `/pages/student/survey/survey?readonly=1&studentId=${encodeURIComponent(item.studentId||'')}` })
  }
})


